import { configureStore } from "@reduxjs/toolkit"
import { SET_REMEMBER_ACCOUNT, SET_TOKEN, type ActionTypes } from "./constants"
import { getItem, setItem } from "@util/index";

export interface UserInfo {
  name: string;
  icon: string;
  role: 0 | 1 | 2;
}
export interface StoreState {
  rememberAccount: boolean;
  token: number;
  userInfo: UserInfo | null
}

const REMEMBER_ACCOUNT = "__REMEMBER_ACCOUNT__"
const MOCK_TOKEN = "__MOCK_TOKEN__"
const USERINFO = "__MOCK_USER_INFO__"

const initState: StoreState = {
  rememberAccount: getItem(REMEMBER_ACCOUNT) ? true : false,
  token: getItem(MOCK_TOKEN) || "",
  userInfo: getItem(USERINFO) || null
}

const store = configureStore<StoreState, ActionTypes>({
  reducer: (state = initState, action) => {
    const { type, payload } = action
    // 判断 action
    switch (type) {
      case SET_REMEMBER_ACCOUNT:
        setItem(REMEMBER_ACCOUNT, payload)
        return { ...state, rememberAccount: payload }
      case SET_TOKEN:
        setItem(MOCK_TOKEN, payload)
        return { ...state, token: payload }
      default:
        return state
    }
  },
  devTools: true
})

export default store

